<?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Description: 基地管理
 *
 * @author      Eden
 * @datetime    2016/11/27 21:30
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */

class Base extends ADM_Controller
{

    private $error = '';

    const PAGE_SIZE = 10;

    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
    }

    public function del()
    {
        $send['state'] = false;
        do {

            $id = intval($this->input->post('id'));
            if ($id == 0) {
                $send['error'] = '官方基地不允许被删除';
                break;
            }

            $db =clone($this->db);
            $db->where('id', $id);
            $db->update('base', ['status' => 0]);
            if ($db->affected_rows()) {
                $send['state'] = true;
            } else {
                $send['error'] = '基地删除失败';
            }

        } while(false);
        $this->output->send($send);
    }

    /**
     * 列表页
     */
    public function index()
    {

        $page = $this->input->get('page');
        $page = intval($page) > 0 ? intval($page) : 1;
        $offset = ($page - 1) * self::PAGE_SIZE;
        $this->load->model('admin/base/Common_Model', 'base');
        $res = $this->base->getLists($offset, self::PAGE_SIZE);
        $data = array();
        if (!$res) {
            $data['total'] = 0;
            $data['data'] = [];
        } else {
            $data['total'] = intval($res['total']);
            $data['data'] = $res['data'];
        }

        $this->load->library('core/Page', null, 'page');
        $this->load->view(parent::TMP_DIR . '/base/index.html', array(
            'data' => $data['data'],
            'page' => $this->page->getPage('/farm/base/index', $res['total'], self::PAGE_SIZE)
        ));
    }

    /**
     * 接口获取基地
     */
    public function api()
    {
        $send['state'] = false;
        do {

            $page = $this->input->get('page');
            $page = intval($page) > 0 ? intval($page) : 1;
            $offset = ($page - 1) * self::PAGE_SIZE;
            $this->load->model('admin/base/Common_Model', 'base');
            $res = $this->base->getLists($offset, self::PAGE_SIZE);
            $data = array();
            if (!$res) {
                $data['totalPage'] = 1;
                $data['nowPage'] = 1;
                $data['data'] = [];
            } else {
                $data['totalPage'] = ceil($res['total'] / self::PAGE_SIZE);
                $data['nowPage'] = $page;
                $data['data'] = $res['data'];
            }

            $send['state'] = true;
            $send['data'] = $data;
        } while(false);
        $this->output->send($send);
    }

    public function add()
    {
        $this->load->view(parent::TMP_DIR . '/base/detail.html', array(
            'baseId' => $this->baseId ? $this->baseId : 0,
            'pageType' => 'add'
        ));
    }

    /**
     * 编辑
     */
    public function edit()
    {
        $baseId = $this->input->get('baseId');

        $this->load->model('admin/base/Common_Model', 'base');
        $res = $this->base->checkExists($baseId);
        if (!$res) {
            show_404();
            exit;
        }
        $this->load->view(parent::TMP_DIR . '/base/edit.html', array(
            'baseId' => $baseId,
            'pageType' => 'edit'
        ));
    }

    public function mod()
    {
        $baseId = $this->input->get('baseId');

        $this->load->model('admin/base/Common_Model', 'base');
        $res = $this->base->checkExists($baseId);
        if (!$res) {
            show_404();
            exit;
        }

        $this->load->view(parent::TMP_DIR . '/base/base.html', array(
            'baseId' => $baseId,
            'pageType' => 'mod'
        ));
    }

    /**
     * 获取基地详情
     */
    public function getDetail()
    {
        $baseId = $this->input->get('baseId');

        $this->load->model('admin/base/Common_Model', 'base');
        $res = $this->base->getDetail($baseId);

        if ($res) {

            $res['fullPath'] = '';
            if (!empty($res['thumb'])) {
                $res['fullPath'] = thumb($res['thumb'], 320, 180);
            }

            $this->output->send(array(
                'state' => true,
                'data' => $res
            ));
        } else {
            $this->output->send(array(
                'state' => false,
                'error' => '详情获取失败'
            ));
        }

    }

    public function upThumb()
    {
        $send['state'] = false;
        do {
            $this->load->helper('func');
            $res = local($_FILES['file']);
            if ($res) {
                $send['state'] = true;
                $send['data'] = array_merge($res, array('url' => thumb($res['key'], 320, 180)));
            } else {
                $send['error'] = '图片上传失败';
            }
        } while(false);

        $this->output->send($send);
    }


    /**
     * 添加农场
     */
    public function doAdd()
    {
        $send['state'] = false;
        do {

            $params = $this->input->post();
            if (!$this->_checkParams($params)) {
                $send['error'] = $this->error;
                break;
            }

            if (empty($params['email'])) {
                $send['error'] = '管理员邮箱不能为空';
                return false;
            }

            if (empty($params['password'])) {
                $send['error'] = '管理员密码不能为空';
                return false;
            }

            // admin exists
            $this->load->model("common/Admin_Model", 'admin');
            if ($this->admin->checkExists($params['email'])) {
                $send['error'] = '管理员邮箱已经存在';
                break;
            }

            $this->load->model('admin/base/Common_Model', 'base');
            $res = $this->base->add($params);
            if ($res) {

                // add admin user
                $this->admin->addItem($params, $res);

                $this->load->model('admin/goods/Express_Model', 'e');
                $this->e->setDefaultExp($res['id']);

                $send['state'] = true;
                $send['data'] = $res;

                @statIncr('baseIncr');
                break;
            }

            $send['error'] = '添加失败';

        } while(false);
        $this->output->send($send);
    }

    /**
     * 删除操作
     */
    public function doEdit()
    {
        $send['state'] = false;
        do {
            $params = $this->input->post();
            if (empty($params['baseId'])) {
                $send['error'] = '该基地不存在';
                break;
            }

            if (!$this->_checkParams($params)) {
                $send['error'] = $this->error;
                break;
            }

            if (!empty($params['pageType']) && $params['pageType'] != 'mod') {
                if (empty($params['email'])) {
                    $send['error'] = '管理员邮箱不能为空';
                    return false;
                }

                if (!empty($params['password'])) {
                    if (strlen($params['password']) < 6) {
                        $send['error'] = '密码长度不能小于6位';
                        break;
                    }

                    // 改密码
                    $pass = encryptPassword($params['password']);
                    $this->load->model('common/Admin_Model', 'a');
                    $res = $this->a->modPass($this->detail['adminId'], $pass['password'], $pass['salt']);
                    if (!$res) {
                        $send['error'] = '密码修改失败';
                        break;
                    }
                }
            }

            $this->load->model('admin/base/Common_Model', 'base');
            $res = $this->base->edit($params);
            if ($res) {
                $send['state'] = true;
                $send['data'] = $res;
                break;
            }

            $send['error'] = '编辑失败';

        } while(false);
        $this->output->send($send);
    }

    /**
     * 检查参数
     * @param array $params
     * @return bool
     */
    private function _checkParams($params = array())
    {

        if (empty($params['baseName'])) {
            $this->error = '基地名称不能为空';
            return false;
        }

        if (empty($params['charger'])) {
            $this->error = '基地负责人姓名不能为空';
            return false;
        }

        if (!empty($params['telephone']) && !preg_match('/^0\d{2,3}-?\d{7,8}$/', $params['telephone'])
            && !preg_match('/^400-([0-9]){1}([0-9-]{7})$/', $params['telphone'])) {
            $this->error = '电话号码格式错误';
            return false;
        }

        if (empty($params['phone'])) {
            $this->error = '手机号不能为空';
            return false;
        }

        if (empty($params['address'])) {
            $this->error = '基地地址不能为空';
            return false;
        }

        if (!preg_match('/^1[34578]\d{9}$/', $params['phone'])) {
            $this->error = '手机号格式错误';
            return false;
        }

        if (empty($params['content'])) {
            $this->error = '基地介绍不能为空';
            return false;
        }

        if ($params['slider'] == 'false') {
            $params['slider'] = 0;
        } else {
            $params['slider'] = 1;
        }

        return true;
    }

}

